﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using agsXMPP;
using agsXMPP.protocol.client;
using System.Collections.Generic;



namespace WebClient
{
    public partial class _Default : System.Web.UI.Page
    {
        XmppClientConnection xmpp;
        
        static bool ingelogd = false;
        static bool uitgelogd = false;
        static bool contactPersonenGeladen = false;
        private static bool nieuwBericht = false;
        private static List<string> berichten = new List<string>();
        static List<string> contactpersonen = new List<string>();
        static Dictionary<string, Presence> status = new Dictionary<string, Presence>();
        static ArrayList onlineUsers = new ArrayList();
        private static User selectedUser;


        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Button voor inloggen.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdLogin_Click(object sender, EventArgs e)
        {
            inloggen();

        }

        /// <summary>
        /// Handelt het inloggen af hahah piemel
        /// </summary>
        private void inloggen()
        {
            xmpp = (XmppClientConnection)Application["xmpp"];
            if (xmpp == null)
            {
                xmpp = new XmppClientConnection();
                Application["xmpp"] = xmpp;
            }

            xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
            //  xmpp.OnRosterItem += new XmppClientConnection.RosterHandler(xmpp_OnRosterItem);
            //xmpp.OnRosterEnd += new ObjectHandler(xmpp_OnRosterEnd);
            xmpp.OnPresence += new PresenceHandler(xmpp_OnPresence);
            xmpp.OnMessage += new MessageHandler(xmpp_OnMessage);

            xmpp.AutoPresence = true;
            xmpp.AutoResolveConnectServer = true;
            xmpp.Port = 5222;
            xmpp.Server = "gmail.com";
            xmpp.ConnectServer = "talk.google.com";
            xmpp.Username = "timo.hermans";
            xmpp.Password = "spek44spek";
            xmpp.Open();

            timInlog.Enabled = true;
        }

        void xmpp_OnMessage(object sender, Message msg)
        {
            if (msg.Body == null)
                return;
            //berichten.Add(String.Format("[{0}] van: {1}", DateTime.Now, msg.From.Bare));
            //berichten.Add(msg.Body);
            selectedUser.Conversatie.Add(String.Format("[{0}] van: {1} zegt: {2}", DateTime.Now, msg.From.Bare, msg.Body));
            nieuwBericht = true;
        }

        void xmpp_OnPresence(object sender, Presence pres)
        {
            switch (pres.Type)
            {
                case PresenceType.available:
                case PresenceType.error:
                case PresenceType.invisible:
                case PresenceType.probe:
                // case PresenceType.subscribe:
                // case PresenceType.subscribed:
                case PresenceType.unavailable:
                    // case PresenceType.unsubscribe:
                    // case PresenceType.unsubscribed:
                    break;
                default:
                    return;
            }


            User user = null;
            foreach (User u in onlineUsers)
            {
                if (u.Jid.Bare == pres.From.Bare)
                {
                    user = u;
                    user.Status = pres.Show;
                    user.StatusText = pres.Status;
                    user.Type = pres.Type;
                    break;
                }
            }
            if (user == null)
            {
                user = new User(pres.From, pres.Show, pres.Status, pres.Type);
                addUserToList(user);
            }
            contactPersonenGeladen = true;
        }

        private int addUserToList(User user)
        {
            //contactpersonen.Add(user.Jid.Bare);
            return onlineUsers.Add(user);
        }

        private void removeUserFromList(User user)
        {
            int index = onlineUsers.IndexOf(user);
            // contactpersonen.RemoveAt(index);
            onlineUsers.RemoveAt(index);
        }

        //private void updateUser(User user)
        //{
        //    int index = onlineUsers.IndexOf(user);
        //    //contactpersonen[index] = getUserString(user);
        //   //contactpersonen.Add(getUserString(user));
        //}

        private string getUserString(User user)
        {
            string status = "";
            switch (user.Status.ToString().ToLower())
            {
                case "none":
                case "chat":
                    status = "Online";
                    break;
                case "dnd":
                    status = "Bezet";
                    break;
                case "away":
                case "xa":
                    status = "Afwezig";
                    break;
                default:
                    status = user.Status.ToString();
                    break;
            }
            string available = "";
            switch (user.Type)
            {
                case PresenceType.available:
                    available = "Online";
                    break;
                case PresenceType.unavailable:
                    available = "Offline";
                    break;
            }
            return user.Jid.Bare + ": " + status + "(" + available + ")";
        }

        void xmpp_OnRosterEnd(object sender)
        {
            contactPersonenGeladen = true;
        }

        void xmpp_OnRosterItem(object sender, agsXMPP.protocol.iq.roster.RosterItem item)
        {
            //lbContact.Items.Add(String.Format("Received Contact {0}", item.Jid.Bare));
            //contactpersonen.Add(String.Format("Received Contact {0}", item.Jid.Bare));
            contactpersonen.Add(item.Jid.User.ToString());
            

        }

        /// <summary>
        /// Event wanneer is ingelogd.
        /// </summary>
        /// <param name="sender"></param>
        void xmpp_OnLogin(object sender)
        {
            ingelogd = true;
            uitgelogd = false;
        }

        /// <summary>
        /// Button voor uitloggen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdLogout_Click(object sender, EventArgs e)
        {
            uitloggen();
        }

        /// <summary>
        /// Handelt het uitloggen af
        /// </summary>
        private void uitloggen()
        {
            xmpp = (XmppClientConnection)Application["xmpp"];

            xmpp.OnLogin -= xmpp_OnLogin;
            xmpp.OnRosterItem -= xmpp_OnRosterItem;
            xmpp.OnRosterEnd -= xmpp_OnRosterEnd;

            xmpp.OnClose += new ObjectHandler(xmpp_OnClose);
            timInlog.Enabled = true;
            xmpp.Close();
            xmpp = null;
        }

        /// <summary>
        /// Event wanneer is uitgelogd.
        /// </summary>
        /// <param name="sender"></param>
        void xmpp_OnClose(object sender)
        {
            ingelogd = false;
            uitgelogd = true;
        }

        /// <summary>
        /// Check voor updates
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            if (ingelogd)
            {
                Label1.Text = "ingelogd";
                Panel1.Visible = true;
            }

            if (contactPersonenGeladen)
            {
                lbContact.Items.Clear();

                foreach (User u in onlineUsers)
                {
                    lbContact.Items.Add(getUserString(u));
                }
                contactPersonenGeladen = false;
            }

            //if (nieuwBericht)
            //{
            //    foreach (string bericht in berichten)
            //    {
            //        LbBerichten.Items.Add(bericht);
            //    }
            //    berichten.Clear();
            //    nieuwBericht = false;
            //}

            if (nieuwBericht)
            {
                LbBerichten.Items.Clear();
                foreach (string bericht in selectedUser.Conversatie)
                {
                    LbBerichten.Items.Add(bericht);
                }
                nieuwBericht = false;
            }

            if (uitgelogd)
            {
                Label1.Text = "uitgelogd";
                Panel1.Visible = false;
                lbContact.Items.Clear();
            }
            UpdatePanel1.Update();
        }

        /// <summary>
        /// Versturen van een bericht.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnVerzend_Click(object sender, EventArgs e)
        {
            nieuwBericht = true;
            string bericht = TbBericht.Text;
            string ontvanger = selectedUser.Jid.Bare;
            xmpp = (XmppClientConnection)Application["xmpp"];
            Message message = new Message(ontvanger, MessageType.chat, bericht);
            xmpp.Send(message);
           
            TbBericht.Text = ""; 
            selectedUser.Conversatie.Add(String.Format("[{0}] van: {1} zegt: {2}", DateTime.Now, selectedUser.Jid.Bare, message.Body));
        }

        protected void lbContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (onlineUsers.Count > 0)
            {
                //int index = lbContact.SelectedIndex;
                //User user = (User) onlineUsers[index];
                int index2 = lbContact.SelectedIndex;
                selectedUser = (User)onlineUsers[index2];
                WeergevenConversatie(selectedUser);
            }
        }

        /// <summary>
        /// De conversatie van een User wordt weergegeven in het berichtenveld.
        /// </summary>
        /// <param name="selectedUser"></param>
        private void WeergevenConversatie(User selectedUser)
        {
            LbBerichten.Items.Clear();
            foreach (string bericht in selectedUser.Conversatie)
            {
                LbBerichten.Items.Add(bericht);
            }
        }

        /// <summary>
        /// Verander de status naar de ingegeven waarde
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DropDownStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            xmpp = (XmppClientConnection)Application["xmpp"];

            switch (DropDownList1.SelectedValue.ToString())
            {
                case "Online":
                    xmpp.Show = ShowType.NONE;
                    break;
                case "Busy":
                    xmpp.Show = ShowType.dnd;
                    break;
                case "Away":
                    xmpp.Show = ShowType.away;
                    break;
                default:
                    break;
            }
            xmpp.SendMyPresence();
        }

        

    }
}